from detection import *
from imageSolver import *

import flask
from flask import Flask, request,json
from flask_cors import *
import random
import urllib
import codecs

app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route('/')
def hello_world():
    return flask.render_template('index.html')

@app.route('/face', methods=['get'])
def faceIn():
    imgName = request.args.to_dict().get('id')
    imgName =  saveImg(imgName)
    dictionary = faceDiscern(imgName);
    result ={"code": 200, "url": dictionary["path"],"faceNum":dictionary["faceNum"],"msg": "成功"}
    print("查看返回",result)
    return json.dumps(result)

def saveImg(url):
    bytes = urllib.request.urlopen(url)
    name = random.randint(1, 20000);
    f = codecs.open(r'./imgs/'+str(name)+'.jpg','wb')  # 代开一个文件，准备以二进制写入文件
    f.write(bytes.read())  # write并不是直接将数据写入文件，而是先写入内存中特定的缓冲区
    f.flush()  # 将缓冲区的数据立即写入缓冲区，并清空缓冲区
    f.close()  # 关闭文件
    return './imgs/'+str(name)+'.jpg';

def faceDiscern(img):
    detector = Detector(modelPath='./infer_model',USE_CUDA=False)
    imgs,bboxes_pre = detector(imgList = [img],confidence_threshold = 0.5,nms_threshold = 0.3)
    faceNum = len(bboxes_pre[0]);
    oldImg = cv2.imread(img)
    #for i,(img,bbox_pre) in enumerate(zip(imgs,bboxes_pre)):
    for i,(img,bbox_pre) in enumerate(zip(imgs,bboxes_pre)):
        path = f'static/img/{i+random.randint(1, 20000)}_out.png';
        #draw_bbox(img, bbox_pre, savePath=path)
        draw_bbox2(oldImg, bbox_pre, savePath=path)
        return {"path":path,"faceNum":faceNum};


if __name__ == '__main__':
    app.run(host = "0.0.0.0",port = int("5000"),debug=True)